package com.mjk.common.tools.plumelog.service.controller.collect.impl;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.client.naming.NacosNamingService;
import com.mjk.common.tools.logger.BizLogger;
import com.mjk.common.tools.plumelog.service.controller.collect.ILogCollect;
import com.mjk.common.tools.springextend.BeeSpringBean;
import com.mjk.common.util.ComputerUtils;
import com.mjk.common.util.HttpUtils;
import com.mjk.common.util.ObjectUtils;
import com.plumelog.core.client.AbstractServerClient;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * 基于nacos分布式配置中心的日志收集功能
 * 通过注册中心获取服务信息，分别对不同服务发送获取日志信息，在进行汇总
 */
@Configuration
@ConditionalOnProperty(name = "spring.cloud.nacos.discovery.enabled", havingValue = "true", matchIfMissing = false)
public class NacosLogCollectImpl implements ILogCollect {
    @Autowired
    private AbstractServerClient abstractServerClient;

    /**
     * 节点端口
     */
    @Value(value = "${server.port:8080}")
    private int nodePort;

    /**
     * 节点端口
     */
    @Value(value = "${spring.application.name:manager}")
    private String nodeName;

    public String collectLog(String indexStr, String queryStr,String from,String size){
        return getServices(indexStr,queryStr,from,size);
    }


    public String getServices(String indexStr, String queryStr,String from,String size) {
        JSONObject queryJson = JSON.parseObject(queryStr);
        try {
            ComputerUtils.ComputerInfo computerInfo = ComputerUtils.getComputerInfo();
            if(queryJson.containsKey("node")){//如果有节点信息
                //判断是否是本节点
                if(queryJson.get("node").equals(computerInfo.getIp()+":"+nodePort)){
                    return abstractServerClient.get(indexStr,queryStr,queryJson.getString("form"),queryJson.getString("size"));
                }
            }else {
                NacosDiscoveryProperties nacosDiscoveryProperties = BeeSpringBean.getBean(NacosDiscoveryProperties.class);
                NacosNamingService nacosNamingService = new NacosNamingService(nacosDiscoveryProperties.getNacosProperties());
                //获取所有的服务名称
                //ListView<String> services = nacosNamingService.getServicesOfServer(0,100);
                Set<ServiceInfo> infos = new HashSet<>();
                //if(ObjectUtils.isNotEmpty(services) && !CollectionUtils.isEmpty(services.getData())){
                //for(String serviceName : services.getData()){
                List<Instance> instances = nacosNamingService.getAllInstances(nodeName);
                instances.forEach(instance -> {
                    //排除本次请求节点
//                    if (computerInfo.getIp().equals(instance.getIp()) && nodePort == instance.getPort()) {
//                        //do noting
//                    } else {
                        ServiceInfo info = new ServiceInfo(instance.getIp(), instance.getPort() + "");
                        infos.add(info);
//                    }
                });
                if (!CollectionUtils.isEmpty(infos)) {
                    //遍历所有的服务节点获取查询信息
                    for (ServiceInfo service : infos) {
                        Map<String,Object> params = new HashMap<>();
                        queryJson.put("node", service.getIp()+":"+service.getPort());//放入节点信息
                        queryJson.put("form",from);
                        queryJson.put("size",size);
                        String result = HttpUtils.httpPost("http://" + service.getIp() + ":" + service.getPort() + "/clientQuery", queryJson.toString(), null);
                        //如果不为空，查询到数据，就跳出循环
                        if (ObjectUtils.isNotEmpty(result)) {
                            return result;
                        }
                    }
                }
            }
            return abstractServerClient.get(indexStr,queryStr,from,size);
        } catch (Exception e) {
            BizLogger.error(e);
        }
        return "";
    }

    @Data
    public static class ServiceInfo {
        public ServiceInfo(String ip,String port){
            this.ip = ip;
            this.port = port;
        }
        private String ip;//服务的IP地址

        private String port;//服务的端口号

        @Override
        public boolean equals(Object obj) {
            if (this == obj) {
                return true;
            }
            if (obj == null || obj.getClass() != this.getClass()) {
                return false;
            }
            ServiceInfo rectangle = (ServiceInfo) obj;
            return this.ip.equals(rectangle.ip) && this.port.equals(rectangle.port);
        }

        @Override
        public int hashCode() {
            int value = Objects.hash(ip,port);
            return value;
        }
    }
}
